const express = require('express');
const cp = require('child_process'); // 可自动打开浏览器模块
const app = express();
const path = require('path');
const fs = require('fs');

let configurl = 'C:\\风机\\数据接收软件参数配置文件.txt'
let mqtturl = 'C:\\风机\\MQTT参数设置.txt'

// 本地文件配置
function MqttApi(Curl,Murl) {
    var dataConfig = fs.readFileSync(Curl)
    var dataMqtt = fs.readFileSync(Murl)
    let dataConfigStr = dataConfig.toString()
    let dataMqttStr = dataMqtt.toString()
    let arrC1 = dataConfigStr.split('|')
    let arrC2 = []
    if (arrC1.length % 13 == 1) {
        for (let i = 0; i < arrC1.length; i++) {
            if (i % 13 == 9) {
                arrC2.push(arrC1[i].substring(0,8))
            }
        }
    }


    let arrM1 = dataMqttStr.split('|')
    let arrM2 = [arrM1[0],arrM1[1],arrM1[2],arrM1[3]]

    let dataObj = {
        config: arrC2,
        mqtt: arrM2
    }
    return JSON.stringify(dataObj) 
}

let data = MqttApi(configurl, mqtturl)
//   /three 返回本地mqtt配置
app.get('/three',(req,res) => {
    res.send(data);
})

app.use(express.static(path.join(__dirname, '../dist')));
app.listen(8889, '127.0.0.1')
console.log('服务器开启成功');
console.log('浏览器访问:http://localhost:8889');
cp.exec("start http://localhost:8889")